import {ListModel, Me, Model, ModelClazz, Net, Plugin} from "mvx-foundation";
import {WXDBManager} from "mvx-uni-app";
import {RegisterAutoLogin} from "./api/RegisterAutoLogin";
import {WXHttpBuilderCreator} from "./api/WXHttpBuilder";

const BaseUrl = "http://tmarketingapi.newhope.cn";
export class TheApp {
  private static registered: boolean = false;
  private static pluginName_: string = "TheApp";

  public static plugin(): Plugin {
    if (this.registered) {
      return Plugin.getBy(this.pluginName_)
    }

    Plugin.register(this.pluginName_);
    let plugin = Plugin.getBy(this.pluginName_);
    plugin.setDBManager(new WXDBManager(plugin));

    let mainNet = new Net(plugin, BaseUrl);
    mainNet.setToMainNet();
    plugin.setMainNet(mainNet);

    mainNet.setHttpBuilderCreator(WXHttpBuilderCreator(true));
    RegisterAutoLogin(mainNet);

    this.registered = true;

    return plugin;
  }


  public static async getModel<T extends Model>(modelClazz: ModelClazz<T>): Promise<T> {
    return (await TheApp.plugin().mf().getModel(modelClazz))
  }

  public static async me(): Promise<string> {
    return String(await (await TheApp.plugin().mf().getModel(Me)).uid())
  }

  public static async listModel(): Promise<ListModel> {
    return (await TheApp.plugin().mf().getModel(ListModel))
  }
}